package com.atguigu.gmall.order.listener;

import com.atguigu.gmall.common.consts.RabbitConst;
import com.atguigu.gmall.order.biz.OrderService;
import com.atguigu.gmall.rabbit.component.RabbitService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @Author:lyd
 **/
@Service
public class OrderDeductWareStockListener {
    @Autowired
    RabbitService rabbitService;
    @Autowired
    OrderService orderService;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = RabbitConst.QUEUE_WARE_ORDER, durable = "true", autoDelete = "false", exclusive = "false"),
            exchange = @Exchange(value = RabbitConst.EXCHANGE_DIRECT_WARE_ORDER, durable = "true", type = ExchangeTypes.TOPIC,
                    autoDelete = "false", internal = "false"),
            key = RabbitConst.ROUTING_KEY_WARE_ORDER
    ))
    public void handle(Message message, Channel channel) throws IOException {
        try {
            orderService.orderDeductWareStock(message, channel);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            rabbitService.retry(message, channel, 5);
        }
    }
}
